﻿using GeometRi;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorksStudy.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Security.Policy;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using View = SolidWorks.Interop.sldworks.View;
using Paine.SolidWorks.Base;
using Demo;
namespace SolidWorksStudy
{
    public partial class FrmMain : Form
    {
        SldWorks swApp;
        ModelDoc2 swModel;
        AssemblyDoc asemDoc;
        ModelDoc2 activeDoc;
        int mateConcidentIndex; //配合重合索引
        int mateParaIndex;      // 平行索引
        int matePerpIndex;  // 垂直索引
        public FrmMain()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp != null)
            {
                string msg = "Message from C# . SolidWorks version is " + swApp.RevisionNumber();

                swApp.SendMsgToUser(msg);
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();

            if (swApp == null)
            {
                return;
            }
            // 获得默认模板路径
            string partDocumentTemplate = swApp.GetDocumentTemplate(1, "", 0, 0, 0);

            var newDoc = swApp.NewDocument(partDocumentTemplate, 0, 0, 0);

            if (newDoc == null)
            {
                return;
            }
            swApp.SendMsgToUser("Create done");

            // 获取当前活跃文档
            ModelDoc2 swModel = (ModelDoc2)(ModelDoc2)swApp.ActiveDoc;

            // 选择对应的草图基准面
            bool boolStatus = swModel.Extension.SelectByID("Plane1", "PlANE", 0, 0, 0, false, 0, null);

            // 创建2d草图
            swModel.SketchManager.InsertSketch(true);

            // 绘制长度100mm的线 （soliworks 系统单位是m，所以是0.1m）
            swModel.SketchManager.CreateLine(0, 0, 0, 0.1, 0, 0);

            // 关闭草图
            swModel.SketchManager.InsertSketch(true);

            // 保存配件
            string myNewPartPath = @"D:\Study\myNewPart.SLDPRT";
            int longStatus = swModel.SaveAs3(myNewPartPath, 0, 1);
            swApp.SendMsgToUser("Document has been Saved");
            // 关闭配件
            swApp.CloseDoc(myNewPartPath);
            swApp.SendMsgToUser("Document Closed");

            // 打开配件
            swApp.OpenDoc(myNewPartPath, 1);
            swApp.SendMsgToUser("Document Opened");

        }

        private void btnGetDocData_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            // 获取当前零件
            ModelDoc2 activeDoc = (ModelDoc2)(ModelDoc2)swApp.ActiveDoc;

            // 获取通用属性值
            string customInfoValue = activeDoc.GetCustomInfoValue("", "设计");
            swApp.SendMsgToUser(customInfoValue);

            activeDoc.AddCustomInfo3("", "NewCustom", 30, "My new custom value");

            swApp.SendMsgToUser("Add Success!");

            var configNames = (string[])activeDoc.GetConfigurationNames();

            foreach (var configName in configNames)
            {
                Debug.Print(configName);
            }

        }

        private void btnChangeDim_Click(object sender, EventArgs e)
        {
            ISldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            ModelDoc2 activeModel = (ModelDoc2)(ModelDoc2)swApp.ActiveDoc;

            // 1 增加配置
            string newConfigName = "NewConfig";
            bool status = activeModel.AddConfiguration2(newConfigName, "", "", true, false, false, true, 256);
            activeModel.ShowConfiguration2(newConfigName);

            // 2  增加特征

            //选择面
            status = activeModel.Extension.SelectByRay(-8.23096562385217E-04, 0, 0.188305076643189, -0.503077026443471, 0.646038297583205, -0.57406273483008, 3.32034055908197E-04, 2, false, 0, 0);

            //Feature feature = activeModel.FeatureManager.FeatureFillet3();


        }

        // 遍历装配体当中的零件
        private void btnGetPartInAssem_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            if (swApp == null)
            {
                return;
            }
            // 获取文档对象为装配体对象
            AssemblyDoc assemDoc = null;

            ModelDoc2 activeModel = (ModelDoc2)swApp.ActiveDoc;
            ModelDocExtension modelExt = activeModel.Extension;
            if (activeModel.GetType() == 2)
            {
                assemDoc = activeModel as AssemblyDoc;
            }
            else
            {
                MessageBox.Show("获取当前装配体文档失败");
                return;
            }
            Feature refPlaneTop = (Feature)assemDoc.FeatureByName("柜顶基准");
            Feature refPlaneBottom = (Feature)assemDoc.FeatureByName("始端基准");
            refPlaneTop.Select2(true, 0);
            refPlaneBottom.Select2(true, 0);

            // 获得零件数量

            object[] objComps = (object[])assemDoc.GetComponents(false);
            int partCount = objComps.Count();
            Debug.Print("Part Count: " + partCount.ToString());
            for (int i = 0; i < partCount; i++)
            {
                Component2 componet = (Component2)objComps[i];
                if (componet.Name.Contains("始端"))
                {
                    Debug.Print(componet.Name);
                    Feature rightBasePlaneFeature = componet.FeatureByName("右视基准面");
                    rightBasePlaneFeature.Select2(true, 0);
                    //Utility.CreateMate();
                    continue;
                }
                else if (componet.Name.Contains("柜顶伸出"))
                {
                    Debug.Print(componet.Name);
                    Feature rightBasePlaneFeature = componet.FeatureByName("右视基准面");
                    rightBasePlaneFeature.Select2(true, 0);
                    continue;
                }
                else
                {
                    continue;
                }

            }
            swApp.CommandInProgress = false;

        }

        private void btnGetPonent_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            ModelDoc2 activeModel = (ModelDoc2)swApp.ActiveDoc;

            // 获取文档对象为装配体对象
            AssemblyDoc assemDoc = null;

            if (activeModel.GetType() == 2)
            {
                assemDoc = activeModel as AssemblyDoc;
            }
            else
            {
                return;
            }
            Component2 component = assemDoc.GetComponentByName("PlugLED-1");

            if (component != null)
            {
                Debug.Print(component.Name + "   " + component.GetPathName());
                component.Select(false);
            }

            // 替换零件 将方框LED转为圆形LED
            string newPart = "D:\\Model\\源文件-SOLIDWORKS API 二次开发实例详解\\ModleAsbuit\\第8章\\RectanglePlug\\PlugLEDForReplace.SLDPRT";

            component.Select(false);
            assemDoc.ReplaceComponents(newPart, "默认", true, true);



        }

        private void btnGetPartFeature_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            ModelDoc2 activeModel = (ModelDoc2)swApp.ActiveDoc;

            // 获取文档对象为零件对象


            object[] featureObjs = (object[])activeModel.FeatureManager.GetFeatures(false);
            if (featureObjs.Count() != 0)
            {
                foreach (object featureObj in featureObjs)
                {
                    Feature feature = featureObj as Feature;
                    Debug.Print(feature.Name);
                }

            }

        }

        private void btnMate_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            ModelDoc2 activeDoc = (ModelDoc2)swApp.ActiveDoc;

            if (activeDoc == null)
            {
                Debug.Print("ActiveDoc is NULL");
                return;
            }
            AssemblyDoc assemDoc = null;

            if (activeDoc.GetType() == 2)
            {
                assemDoc = (AssemblyDoc)activeDoc;
            }

            string partInsert = "D:\\Model\\源文件-SOLIDWORKS API 二次开发实例详解\\ModleAsbuit\\RectanglePlug\\PlugButton.SLDPRT";
            // 插入新零件
            ModelDoc2 partDocInsert = swApp.OpenDoc6(partInsert, 1, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0);
            if (partDocInsert == null)
            {
                Debug.Print("Open part insert error");
                return;
            }
            Debug.Print("Part has been inserted");

            swApp.ActivateDoc(activeDoc.GetPathName());

            assemDoc.AddComponent("PlugButton.SLDPRT", 0, 0, 0);
            swApp.CloseDoc(partInsert);

            #region 第一对基准配合
            string MateBaseName1 = "CenterV@PlugButton-1@PowerStrip";
            string MateBaseName2 = "RectangleWireConnectFace@PlugBottomBox-1@PowerStrip";

            // 加入选择
            bool res = activeDoc.Extension.SelectByID(MateBaseName1, "PLANE", 0, 0, 0, false, 1, null);
            bool res2 = activeDoc.Extension.SelectByID(MateBaseName2, "PLANE", 0, 0, 0, true, 1, null);

            // 输出选择结果
            Debug.Print(res.ToString());
            Debug.Print(res2.ToString());

            // 0是距离，5是重合
            int x = 0;
            Mate2 swMate = assemDoc.AddMate5(5, 0, false, 0.02, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out x);
            Feature mateFeature = (Feature)swMate;
            mateFeature.Name = "按钮和插座配合1";



            #endregion

            #region 第二基准面配合

            MateBaseName1 = "CenterH@PlugButton-1@PowerStrip";
            MateBaseName2 = "BoxCenterH@PlugBottomBox-1@PowerStrip";

            // 加入选择
            res = activeDoc.Extension.SelectByID(MateBaseName1, "PLANE", 0, 0, 0, false, 1, null);
            res2 = activeDoc.Extension.SelectByID(MateBaseName2, "PLANE", 0, 0, 0, true, 1, null);

            // 输出选择结果
            Debug.Print(res.ToString());
            Debug.Print(res2.ToString());

            // 0是距离，5是重合
            swMate = assemDoc.AddMate5(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out x);
            mateFeature = (Feature)swMate;
            mateFeature.Name = "按钮和插座配合2";
            #endregion


            #region 第三基准面配合

            MateBaseName1 = "ButtonTop@PlugButton-1@PowerStrip";
            MateBaseName2 = "BoxInnerBottom@PlugBottomBox-1@PowerStrip";

            // 加入选择
            res = activeDoc.Extension.SelectByID(MateBaseName1, "PLANE", 0, 0, 0, false, 1, null);
            res2 = activeDoc.Extension.SelectByID(MateBaseName2, "PLANE", 0, 0, 0, true, 1, null);

            // 输出选择结果
            Debug.Print(res.ToString());
            Debug.Print(res2.ToString());

            // 0是距离，5是重合
            swMate = assemDoc.AddMate5(5, 0, true, 0.02, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out x);
            mateFeature = (Feature)swMate;
            mateFeature.Name = "按钮和插座配合3";
            #endregion
        }

        private void btnGetMate2_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                return;
            }
            ModelDoc2 activeDoc = (ModelDoc2)swApp.ActiveDoc;

            if (activeDoc == null)
            {
                Debug.Print("Active Doc is Null");
                return;
            }

            // 装配体文档
            AssemblyDoc assemDoc = null;
            if (activeDoc.GetType() == 2)
            {
                Debug.Print("Type of Active Doc is Assemble");
                assemDoc = (AssemblyDoc)activeDoc;
            }

            // 零件文档
            PartDoc prtDoc;
            if (activeDoc.GetType() == 1)
            {
                Debug.Print("Type of Active Doc is Part");
                prtDoc = (PartDoc)activeDoc;
            }



            string compName = "PlugSlotA-1"; // 指定被寻找配合的零件
            Component2 component = assemDoc.GetComponentByName(compName);

            if (component == null)
            {
                Debug.Print(compName + " Not Found");
                return;
            }

            object[] mateObjs = (object[])component.GetMates();
            foreach (object mateObj in mateObjs)
            {
                Mate2 mate = (Mate2)mateObj;
                if (mate == null)
                {
                    continue;
                }
                Feature mateFeature = (Feature)mate;

                // 5代表距离 , 0 代表重合
                if (mate.Type == 5)
                {
                    DisplayDimension disDim = mate.DisplayDimension;

                    Dimension disValue = mate.DisplayDimension2[0].GetDimension2(0);
                    double distance = disValue.GetValue2("默认");
                    Debug.Print(mateFeature.Name + ": " + distance);

                }
                if (mate.Type == 0)
                {
                    Debug.WriteLine(mateFeature.Name);
                }
            }
        }

        private void btnCreateAssem_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {
                Debug.Print("Connect Failed");
                return;
            }
            string docTemplate = swApp.GetDocumentTemplate(2, "", 0, 0, 0);

            ModelDoc2 modelDoc = (ModelDoc2)swApp.NewDocument(docTemplate, 0, 0, 0);
            if (modelDoc == null)
            {
                return;
            }
            string pathRoot = "D:\\Model\\源文件-SOLIDWORKS API 二次开发实例详解\\ModleAsbuit\\第8章\\RectanglePlug\\PlugHead\\";
            modelDoc.SaveAs(pathRoot + "DIY-PlugHead.SLDASM");
            Debug.Print("Save Done");

            AssemblyDoc assemDoc = (AssemblyDoc)modelDoc;
            swApp.OpenDoc(pathRoot + "PlugPinHead.SLDPRT", 1);
            swApp.OpenDoc(pathRoot + "PlugPin1.SLDPRT", 1);
            swApp.OpenDoc(pathRoot + "PlugPin2.SLDPRT", 1);


            Component2 headComponent = assemDoc.AddComponent4(pathRoot + "PlugPinHead.SLDPRT", "", 0, 0, 0);
            Component2 pin1Component = assemDoc.AddComponent4(pathRoot + "PlugPin1.SLDPRT", "", 0, 0, 0);
            Component2 pin2Component = assemDoc.AddComponent4(pathRoot + "PlugPin2.SLDPRT", "", 0, 0, 0);

            swApp.ActivateDoc(pathRoot + "DIY-PlugHead.SLDASM");


            #region Pin1配合

            // 配合1 
            //先选中
            string select1 = "CenterV@PlugPin2-1@DIY-PlugHead";
            string select2 = "CenterV@PlugPinHead-1@DIY-PlugHead";

            modelDoc.Extension.SelectByID(select1, "PLANE", 0, 0, 0, false, 0, null);
            modelDoc.Extension.SelectByID(select2, "PLANE", 0, 0, 0, true, 0, null);



            int errorCount = 0;
            Mate2 pin2AndHeadMate1 = assemDoc.AddMate2(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, out errorCount);
            if (pin2AndHeadMate1 == null)
            {
                Debug.Print("Mate1 add failed");
            }

            modelDoc.ClearSelection();
            // 配合2
            select1 = "CenterH@PlugPin2-1@DIY-PlugHead";
            select2 = "CenterH@PlugPinHead-1@DIY-PlugHead";

            modelDoc.Extension.SelectByID(select1, "PLANE", 0, 0, 0, false, 0, null);
            modelDoc.Extension.SelectByID(select2, "PLANE", 0, 0, 0, true, 0, null);

            Mate2 pin2AndHeadMate2 = assemDoc.AddMate2(5, 0, false, 10.3 / 1000.0, 0, 0, 0, 0, 0, 0, 0, out errorCount);
            if (pin2AndHeadMate2 == null)
            {
                Debug.Print("Mate2 add failed");
            }
            modelDoc.ClearSelection();

            // 配合3
            select1 = "ConnectFace@PlugPin2-1@DIY-PlugHead";
            select2 = "ConnectFace@PlugPinHead-1@DIY-PlugHead";

            modelDoc.Extension.SelectByID(select1, "PLANE", 0, 0, 0, false, 0, null);
            modelDoc.Extension.SelectByID(select2, "PLANE", 0, 0, 0, true, 0, null);

            Mate2 pin2AndHeadMate3 = assemDoc.AddMate2(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, out errorCount);
            if (pin2AndHeadMate3 == null)
            {
                Debug.Print("Mate3 add failed");
            }
            modelDoc.ClearSelection();
            #endregion

            #region Pin2配合

            // 配合1
            select1 = "ConnectFace@PlugPin1-1@DIY-PlugHead";
            select2 = "ConnectFace@PlugPinHead-1@DIY-PlugHead";

            modelDoc.Extension.SelectByID(select1, "PLANE", 0, 0, 0, false, 0, null);
            modelDoc.Extension.SelectByID(select2, "PLANE", 0, 0, 0, true, 0, null);

            Mate2 pin1AndHeadMate1 = assemDoc.AddMate2(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, out errorCount);
            if (pin1AndHeadMate1 == null)
            {
                Debug.Print("2 :Mate1 add failed");
            }
            modelDoc.ClearSelection();

            // 配合2
            select1 = "CenterV@PlugPin1-1@DIY-PlugHead";
            select2 = "PinCenterV@PlugPinHead-1@DIY-PlugHead";

            modelDoc.Extension.SelectByID(select1, "PLANE", 0, 0, 0, false, 0, null);
            modelDoc.Extension.SelectByID(select2, "PLANE", 0, 0, 0, true, 0, null);

            Mate2 pin1AndHeadMate2 = assemDoc.AddMate2(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, out errorCount);
            if (pin1AndHeadMate1 == null)
            {
                Debug.Print("2 :Mate2 add failed");
            }
            modelDoc.ClearSelection();

            #endregion
        }

        private void btnDrawSketch_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            if (swApp == null)
            {
                Debug.Print("Connect Failed");
                return;
            }
            ModelDoc2 activeDoc = (ModelDoc2)swApp.ActiveDoc;

            #region 建立凹台
            SketchManager skm = activeDoc.SketchManager;
            Feature topPlane = (Feature)((PartDoc)activeDoc).FeatureByName("TOP");
            topPlane.Select(false);


            // 关闭弹出尺寸修改对话框
            swApp.SetUserPreferenceToggle(10, false);

            // 草图画一个闭环
            skm.InsertSketch(false); // 进入草图编辑模式
            var line1 = skm.CreateLine(0, 0, 0, 0.2, 0, 0);
            var arc1 = skm.CreateTangentArc(0.2, 0, 0, 0.25, 0.05, 0, (int)swTangentArcTypes_e.swForward);
            var line2 = skm.CreateLine(0.25, 0.05, 0, 0, 0.05, 0);
            var line3 = skm.CreateLine(0, 0.05, 0, 0, 0, 0);

            //画线1的智能尺寸
            line1.Select(false);

            DisplayDimension displayDim1 = (DisplayDimension)activeDoc.AddDimension2(0.1, 0, 0.05); // 参数为数字摆放位置
            Dimension line1Dim = displayDim1.GetDimension2(0);
            line1Dim.Name = "刀身长度1";
            line1Dim.SetValue2(1000, 2); // 更改智能尺寸值

            //刀尖的智能尺寸
            arc1.Select(false);
            DisplayDimension arc1DisplayDim = (DisplayDimension)activeDoc.AddDimension2(1.2, 0, 0.02);
            var arc1Dim = arc1DisplayDim.GetDimension2(0);
            arc1Dim.Name = "刀尖弧度";
            arc1Dim.Value = 100;



            Sketch skecth = skm.ActiveSketch;   // 获得当前编辑的草图对象
            Feature feat = (Feature)skecth;     // 强转为草图对象
            feat.Name = "凹台草图";
            skm.InsertSketch(true);// 退出草图编辑模式

            activeDoc.ClearSelection2(true);

            feat = (Feature)((PartDoc)activeDoc).FeatureByName("凹台草图");

            feat.Select(false); // 选中草图

            // 参数4 为终止条件，枚举值  swEndConditions_e  0为拉伸指定值
            feat = activeDoc.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.03, 0, false, false, false, false, 0, 0, false, false, false, false, false, true, true, 0, 0, false);
            feat.Name = "新建凹台";



            #endregion

            #region 挖槽
            activeDoc.ClearSelection2(true);
            activeDoc.Extension.SelectByID2("", "FACE", 0.01, 0.03, -0.01, false, 0, null, 0);

            //插入草图
            skm.InsertSketch(true);
            object[] Retangle1 = (object[])skm.CreateCornerRectangle(0, 0, 0, 0.1, 0.01, 0); // 绘制矩形

            skecth = skm.ActiveSketch;
            skm.InsertSketch(true);
            feat = (Feature)skecth;
            feat.Select(false);
            feat = activeDoc.FeatureManager.FeatureCut3(true, false, false, 0, 0, 0.01, 1, false, false, false, false, 0, 0, false, false, false, false, false, true, true, true, true, false, 0, 0, false);
            feat.Name = "槽口";


            #endregion

            swApp.SetUserPreferenceToggle(10, true);    //激活用户交互窗口
        }


        private void btnTraveSelection_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            swModel = (ModelDoc2)swApp.ActiveDoc;

            SelectionMgr selectionMgr = (SelectionMgr)swModel.SelectionManager;

            int selectObjType = selectionMgr.GetSelectedObjectType3(1, 0);
            swSelectType_e selectType = (swSelectType_e)selectObjType;
            MessageBox.Show(selectType.ToString());

        }
        /// <summary>
        /// 工程图坐标比例关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDrawStudy_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            swModel = (ModelDoc2)swApp.ActiveDoc;

            SketchManager swSketchMgr = swModel.SketchManager;
            SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager;
            MathUtility swMathUtility = (MathUtility)swApp.GetMathUtility();
            DrawingDoc swDrawing = (DrawingDoc)swModel;

            Sheet swSheet = swDrawing.Sheet["图纸1"];

            swDrawing.ActivateSheet("图纸1");

            Feature swFeat1 = (Feature)swDrawing.FeatureByName("");

            swSheet.SetScale(1, 5, false, false); // 设置工程图比例
            //swSketchMgr.AddToDB = true;       // 草图直接添加进数据库

            swDrawing.InsertModelAnnotations3(0, 8, true, true, false, true);

        }

        private void btnGetPartFaceAndHole_Click(object sender, EventArgs e)
        {
            SheetMetal sheetMetal = new SheetMetal();
            sheetMetal.ExportInfo();
        }
        /// <summary>
        /// 创建一个以以参数面上的某点作为对象，创建一个坐标
        /// </summary>
        /// <param name="bigestFace">排的Face对象</param>
        /// <returns></returns>

        private void CountHole(PartDoc prtDoc)
        {
            List<Edge> CircleEdge = new List<Edge>();  // 存放所有的圆环Edge对象
            List<CircleHoleModel> circleHoleModelList = new List<CircleHoleModel>();
            List<Loop2> circleAndSlotLoop = new List<Loop2>();
            object[] bodies = (object[])prtDoc.GetBodies2((int)swBodyType_e.swAllBodies, false);
            foreach (Body2 body in bodies)
            {
                object[] bodyFaces = (object[])body.GetFaces();
                foreach (Face2 face in bodyFaces)
                {
                    object[] loop2List = face.GetLoops() as object[];    // 获得面上所有的环
                    if (loop2List.Length > 0)
                    {
                        foreach (Loop2 loop in loop2List)   // 环对象
                        {
                            var edges = loop.GetEdges() as object[];   // 获得该环的边

                            // 判断是否是圆环
                            if (edges.Length == 1)  // 获得孔,圆孔一条边，,槽口四条边 ?怎么获得槽口？
                            {
                                Edge edge = edges[0] as Edge;
                                Curve curve = (Curve)edge.GetCurve();

                                circleAndSlotLoop.Add(loop);
                                if (curve.IsCircle())
                                {
                                    CircleEdge.Add(edge); // 把圆环加入到列表里
                                    circleAndSlotLoop.Add(loop);
                                }
                            }

                            //// 判断是否是腰孔
                            if (edges.Length == 4)
                            {
                                int arcCount = 0;
                                int lineCount = 0;
                                Curve[] circleCurves = new Curve[2];
                                // 判断腰孔对象
                                for (int i = 0; i < edges.Length; i++)
                                {
                                    Edge edge = edges[i] as Edge;
                                    Curve curve = (Curve)edge.GetCurve();
                                    if (curve != null)
                                    {
                                        if (curve.IsCircle())
                                        {
                                            circleCurves[arcCount] = curve;
                                            arcCount++;
                                        }
                                        else
                                        {
                                            lineCount++;
                                        }
                                    }
                                }
                                if (arcCount == lineCount && arcCount == 2)
                                {
                                    // 判断两个圆曲线半径是否相等，相等即为槽口
                                    var circleParadata0 = circleCurves[0].CircleParams;
                                    var circleParadata1 = circleCurves[1].CircleParams;

                                    //if (circleParadata0[6] == circleParadata1[6])// 两个圆半径不相等，槽口
                                    //{
                                    //    circleAndSlotLoop.Add(loop);
                                    //}

                                    //foreach (Edge edge in edges)
                                    //{

                                    //    edge.Highlight(true);
                                    //}
                                }

                            }

                        }
                    }

                }
            }
            #region 根据找到的圆环构建圆Model
            // 
            int index = 0;
            foreach (Edge circleEdge in CircleEdge)
            {
                //   circleEdge.Highlight(true);
                index++;
                Curve curve = (Curve)circleEdge.GetCurve();

                if (curve != null)
                {
                    double[] circleParams = (double[])curve.CircleParams;


                    // 新建圆孔对象
                    //CircleHoleModel hole = new CircleHoleModel(circleParams[0] * 1000, circleParams[1] * 1000, circleParams[2] * 1000, circleParams[6] * 1000);

                    //    // 检查是否已存在相同的圆孔对象
                    //    // 使用 LINQ 查询是否存在两个以上相等的值
                    //    bool isDuplicate = circleHoleModelList.Any(existingHole =>
                    //        (existingHole.centerX == hole.centerX && existingHole.centerY == hole.centerY && existingHole.centerZ == hole.centerZ)
                    //    );

                    //    if (!isDuplicate)
                    //    {
                    //        // 如果不存在相同 SomeValue 值的圆孔对象，则添加

                    //        circleHoleModelList.Add(hole);

                    //    }

                }

            }
            #endregion
            foreach (Loop2 loop in circleAndSlotLoop)
            {
                var edges = loop.GetEdges() as object[];
                foreach (Edge edge in edges)
                {
                    edge.Highlight(true);
                }
            }
            Debug.Print(circleAndSlotLoop.Count.ToString());
        }
        private void BtnModeler_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SketchManager swSketchMgr = default(SketchManager);
            SketchSegment sketchSegment = default(SketchSegment);
            SelectionMgr swSelMgr = default(SelectionMgr);
            SketchPoint sketchPoint = default(SketchPoint);
            FeatureManager swFeatureMgr = default(FeatureManager);
            RefPlane refPlane = default(RefPlane);
            Feature swFeat = default(Feature);
            bool status = false;
            object profiles = null;
            object guides = null;
            Feature[] profile = new Feature[2];
            Feature[] guideCurve = new Feature[1];
            Modeler swModeler = default(Modeler);
            Body2 swBody = default(Body2);
            int count = 0;
            object[] featArr = null;
            int i = 0;

            //Open new part document
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModelDocExt = (ModelDocExtension)swModel.Extension;

            //Create closed profile
            status = swModelDocExt.SelectByID2("Front Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swSketchMgr = (SketchManager)swModel.SketchManager;
            sketchSegment = (SketchSegment)swSketchMgr.CreateCircle(0.0, 0.0, 0.0, 0.021796, -0.030937, 0.0);
            sketchPoint = (SketchPoint)swSketchMgr.CreatePoint(0.023454, 0.029699, 0.0);
            swModel.ClearSelection2(true);
            swSketchMgr.InsertSketch(true);

            //Create another closed profile
            status = swModelDocExt.SelectByID2("Front Plane", "PLANE", 0, 0, 0, true, 0, null, 0);
            swFeatureMgr = (FeatureManager)swModel.FeatureManager;
            refPlane = (RefPlane)swFeatureMgr.InsertRefPlane(8, 0.254, 0, 0, 0, 0);
            status = swModelDocExt.SelectByID2("Plane1", "PLANE", 0, 0, 0, false, 0, null, 0);
            sketchSegment = (SketchSegment)swSketchMgr.CreateCircle(-0.035118, -0.014102, 0.0, -0.025452, -0.02953, 0.0);
            sketchPoint = (SketchPoint)swSketchMgr.CreatePoint(-0.018033, -0.020392, 0.0);
            swModel.ClearSelection2(true);
            swSketchMgr.InsertSketch(true);

            //Create guide curve
            status = swModelDocExt.SelectByID2("Point4@Sketch1", "EXTSKETCHPOINT", 0.0234541440502721, 0.0296993303358475, 0, true, 0, null, 0);
            status = swModelDocExt.SelectByID2("Point5@Sketch2", "EXTSKETCHPOINT", -0.0180330744027628, -0.0203923494843098, 0, true, 0, null, 0);
            swModel.ClearSelection2(true);
            status = swModelDocExt.SelectByID2("Point4@Sketch1", "EXTSKETCHPOINT", 0.0234541440502721, 0.0296993303358475, 0, false, 1, null, 0);
            status = swModelDocExt.SelectByID2("Point5@Sketch2", "EXTSKETCHPOINT", -0.0180330744027628, -0.0203923494843098, 0, true, 1, null, 0);
            swModel.Insert3DSplineCurve(false);
            swModel.ClearSelection2(true);

            //Select guide curve and profiles for loft feature
            status = swModelDocExt.SelectByID2("Curve1", "REFERENCECURVES", 0, 0, 0, false, 2, null, 0);
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            Debug.Print("Guide curve name: " + swFeat.Name);
            guideCurve[0] = (Feature)swFeat;
            guides = guideCurve;
            swModel.ClearSelection2(true);
            status = swModelDocExt.SelectByID2("Sketch1", "SKETCH", 0.00984860021145358, 0.0365397341178567, 0, true, 1, null, 0);
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            Debug.Print("Profile name: " + swFeat.Name);
            profile[0] = (Feature)swFeat;
            swModel.ClearSelection2(true);
            status = swModelDocExt.SelectByID2("Sketch2", "SKETCH", -0.0401969362026636, 0.00338231877308527, 0, true, 1, null, 0);
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            Debug.Print("Profile name: " + swFeat.Name);
            profile[1] = (Feature)swFeat;
            profiles = profile;
            swModel.ClearSelection2(true);

            //Create temporary loft body
            swModeler = (Modeler)swApp.GetModeler();
            swBody = (Body2)swModeler.CreateLoftBody2(swModel, profiles, guides, null, false, 0, 0, 0, true, false,
            true, false, true, 1, 1, 1, true, true, 1, 1,
            false);

            // Test whether the loft body is a temporary body
            status = swBody.IsTemporaryBody();
            Debug.Print("Is the loft body a temporary body?  " + status);
            if (status)
            {
                // Display the temporary loft body
                swBody.Display3(swModel, 256, (int)swTempBodySelectOptions_e.swTempBodySelectOptionNone);
                Debug.Print("Temporary loft body displayed; examine the graphics area.");
            }
            else
            {
                Debug.Print("Temporary loft body was not created.");
            }

            Debug.Print("");

            //Verify that the temporary loft body is not a loft feature
            //by examining the list of features printed to the
            //Immediate window
            count = swFeatureMgr.GetFeatureCount(false);
            featArr = (object[])swFeatureMgr.GetFeatures(false);
            for (i = 0; i < count - 1; i++)
            {
                swFeat = (Feature)featArr[i];
                Debug.Print(swFeat.Name);
            }

            swModel.ViewZoomtofit2();

        }

        private void btnExportSheetMetal_Click(object sender, EventArgs e)
        {
            SheetMetal sheetMetal = new SheetMetal();
            sheetMetal.ExportInfo();
        }

        private void btnOverLookingMate_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            if (swApp == null)
            {
                return;
            }
            activeDoc = (ModelDoc2)swApp.ActiveDoc;
            IAssemblyDoc asemDoc = (IAssemblyDoc)activeDoc;
            SelectionMgr selectMgr = (SelectionMgr)activeDoc.SelectionManager;

            if (selectMgr.GetSelectedObjectCount() != 2)
            {
                Debug.Print("Selection Count Error!   " + selectMgr.GetSelectedObjectCount());
                return;
            }


            Entity selectEntity = (Entity)selectMgr.GetSelectedObject6(1, 0);
            Component2 selectComponent = selectEntity.IGetComponent2();
            Feature refPlaneFeat1 = selectComponent.FeatureByName("上视基准面");
            selectEntity = (Entity)selectMgr.GetSelectedObject6(2, 0);
            selectComponent = selectEntity.IGetComponent2();
            Feature refPlaneFeat2 = selectComponent.FeatureByName("上视基准面");

            refPlaneFeat1.Select2(false, 1);
            refPlaneFeat2.Select2(true, 1);

            // 创建重合配合所需对象
            //CoincidentMateFeatureData CoincMateData;
            //object[] EntitiesToMate = new object[2];
            //object EntitiesToMateVar;

            //// 创建重合数据
            //CoincMateData = (CoincidentMateFeatureData)asemDoc.CreateMateData(0);

            //// 将要重合的对象放入到重合数据里面
            //EntitiesToMate[0] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(1, 1);
            //EntitiesToMate[1] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(2, 1);
            //EntitiesToMateVar = EntitiesToMate;
            //CoincMateData.EntitiesToMate = EntitiesToMateVar;

            //// Set the Mate Alignment
            //CoincMateData.MateAlignment = 0;

            //// Create the mate
            //Feature MateFeature = (Feature)asemDoc.CreateMate(CoincMateData);

            //MateFeature.Name = "前视基准重合";
            //activeDoc.ClearSelection2(true);
            //activeDoc.EditRebuild3();

            swApp.CommandInProgress = false;

        }

        // 向量矩阵信息按钮
        private void button3_Click(object sender, EventArgs e)
        {
            mateParaIndex = 0;
            mateConcidentIndex = 0;
            matePerpIndex = 0;

            swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            if (swApp == null)
            {
                return;
            }
            activeDoc = (ModelDoc2)swApp.ActiveDoc;
            asemDoc = (AssemblyDoc)activeDoc;
            SelectionMgr selectMgr = (SelectionMgr)activeDoc.SelectionManager;
            Entity selectEntity = (Entity)selectMgr.GetSelectedObject6(1, 0);


            // 遍历柜顶、始端排
            object[] objComps = (object[])asemDoc.GetComponents(false);
            int partCount = objComps.Count();
            Debug.Print("Part Count: " + partCount.ToString());
            for (int i = 0; i < partCount; i++)
            {

                Component2 currentComponent = (Component2)objComps[i];
                // 非伸出or始端排
                if (!(currentComponent.Name.Contains("柜顶伸出") || currentComponent.Name.Contains("始端")))
                {
                    continue;
                }
                string currentName = currentComponent.Name;
                Debug.Print(currentName);
                int mateType = GetMateType(currentComponent); // 获得需要配合的类型 1 平行，2 垂直

                // 创建侧面基准的配合
                CreateParaOrPerpMate(currentComponent, mateType);

                // 创建柜顶排或始端排与基准面的重合关系
                CreateTopOrBottomConcidentMate(currentComponent);

            }
            activeDoc.EditRebuild3();
            swApp.CommandInProgress = false;
            MessageBox.Show("始端、伸出排基准面创建完成");
        }

        // 创建柜顶伸出排 或 始端排 与“始端基准面”或 “柜顶基准面”的重合关系
        private void CreateTopOrBottomConcidentMate(Component2 selectedComponent)
        {

            //Feature topOrBottomRefPlane = null;
            //// 创建重合数据
            //CoincidentMateFeatureData CoincMateData;
            //CoincMateData = (CoincidentMateFeatureData)asemDoc.CreateMateData(0);
            //Debug.Print(selectedComponent.Name);
            //string mateTypeMsg = "";

            //if (selectedComponent.Name.Contains("始端"))
            //{
            //    mateTypeMsg = "始端基准重合";
            //    topOrBottomRefPlane = (Feature)asemDoc.FeatureByName("始端基准");
            //    CoincMateData.MateAlignment = 1;
            //    //continue;
            //}
            //else if (selectedComponent.Name.Contains("柜顶伸出"))
            //{
            //    mateTypeMsg = "柜顶基准重合";
            //    CoincMateData.MateAlignment = 0;
            //    topOrBottomRefPlane = (Feature)asemDoc.FeatureByName("柜顶基准");
            //}
            //else
            //{
            //    return;
            //}
            //Feature componentRightBasePlaneFeature = selectedComponent.FeatureByName("右视基准面");
            //componentRightBasePlaneFeature.Select2(true, -1);
            //topOrBottomRefPlane.Select2(true, -1); // 选中始端基准or柜顶基准

            //#region 创建重合关系
            //// 创建重合配合所需对象

            //object[] EntitiesToMate = new object[2];
            //object EntitiesToMateVar;



            //// 将要重合的对象放入到重合数据里面
            //EntitiesToMate[0] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(1, 0);
            //EntitiesToMate[1] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(2, 0);
            //EntitiesToMateVar = EntitiesToMate;
            //CoincMateData.EntitiesToMate = EntitiesToMateVar;



            //// Create the mate
            //Feature MateFeature = (Feature)asemDoc.CreateMate(CoincMateData);
            //MateFeature.Name = mateTypeMsg + mateConcidentIndex++;
            //Debug.Print("配合创建成功：" + MateFeature.Name);
            //activeDoc.ClearSelection2(true);
            //#endregion
        }

        /// <summary>
        /// 创建两面的配合关系,调用前先用Feature.Select2()选中两个面，Mark必须是-1
        /// </summary>
        /// <param name="mateType"></param>
        private void CreateParaOrPerpMate(Component2 selectedComponent, int mateType)
        {
            //// 选中测试基准面和零件的上视基准面
            //Feature sideBaseViewFeat = (Feature)asemDoc.FeatureByName("侧面基准");
            //Feature refTopViewFeat = selectedComponent.FeatureByName("上视基准面");
            //refTopViewFeat.Select2(false, -1);   // 零件上视基准面选中
            //sideBaseViewFeat.Select2(true, -1); //装配体侧视基准面选中 必须是-1
            //Feature MateFeature = null;
            //object[] EntitiesToMate = new object[2];

            //if (mateType == 1)   // 平行
            //{
            //    Debug.Print("创建平行关系....");
            //    ParallelMateFeatureData paraMateData = (ParallelMateFeatureData)asemDoc.CreateMateData(3);
            //    // 将要重合的对象放入到重合数据里面
            //    EntitiesToMate[0] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(1, -1); // 必须是-1
            //    EntitiesToMate[1] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(2, -1);
            //    object EntitiesToMateVar = EntitiesToMate;
            //    paraMateData.EntitiesToMate = EntitiesToMateVar;

            //    // Set the Mate Alignment
            //    paraMateData.MateAlignment = 0;

            //    // Create the mate
            //    MateFeature = (Feature)asemDoc.CreateMate(paraMateData);
            //    MateFeature.Name = "侧视基准平行" + mateParaIndex++;
            //    activeDoc.ClearSelection2(true);
            //}
            //else if (mateType == 2) // 垂直
            //{
            //    Debug.Print("创建垂直关系....");

            //    PerpendicularMateFeatureData PerpMateData;
            //    // Create PerpendicularMateFeatureData
            //    PerpMateData = (PerpendicularMateFeatureData)asemDoc.CreateMateData(2);

            //    // Set the Entities To Mate
            //    EntitiesToMate[0] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(1, -1);
            //    EntitiesToMate[1] = ((SelectionMgr)(activeDoc.SelectionManager)).GetSelectedObject6(2, -1);
            //    object EntitiesToMateVar = EntitiesToMate;
            //    PerpMateData.EntitiesToMate = (EntitiesToMateVar);

            //    // Create the mate
            //    MateFeature = (Feature)asemDoc.CreateMate(PerpMateData);
            //    MateFeature.Name = "侧视基准垂直" + matePerpIndex++;
            //    activeDoc.ClearSelection2(true);
            //}
            //Debug.Print("配合创建成功：" + MateFeature.Name);
        }

        /// <summary>
        /// 根据选中零件的上视基准，返回该零件的几何关系
        /// </summary>
        /// <param name="selectedComponent"></param>
        /// <returns>1 平行，2 垂直</returns>
        /// <exception cref="Exception"></exception>
        private int GetMateType(Component2 selectedComponent)
        {
            MathUtility swMathUtil = (MathUtility)swApp.GetMathUtility();
            MathTransform componentTransform = selectedComponent.Transform2; // 获得当前选中组件的变换矩阵

            // 创建排时固定的010 （上视基准面）
            double[] nVector = { 0, 1, 0 };
            object vVector = nVector;
            MathVector originVector = (MathVector)swMathUtil.CreateVector(vVector);
            MathVector transedVector = (MathVector)originVector.MultiplyTransform(componentTransform);


            // x=1||x==-1 代表上视基准与侧面基准平行，y==1||y==-1 代表垂直，z？
            double[] newData = (double[])transedVector.ArrayData;

            double vX = Math.Round(newData[0], 3);
            double vY = Math.Round(newData[1], 3);
            Debug.Print(vX + "  " + vY);

            if (vX == 1 || vX == -1)
            {
                // 表平行关系
                return 1;
            }
            if (vY == 1 || vY == -1)
            {
                // 表垂直关系
                return 2;
            }
            else
            {
                swApp.CommandInProgress = false;
                throw new Exception("未找到侧视配合关系：" + selectedComponent.Name);

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();
            UserProgressBar upb;
            swApp.GetUserProgressBar(out upb);

            upb.Start(0, 100, "进度条显示");

            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(10);
                upb.UpdateProgress(i);
            }
            ModelDoc2 activeDoc = (ModelDoc2)swApp.ActiveDoc;


        }

        private void button4_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();
            swModel = (ModelDoc2)swApp.ActiveDoc;

            SketchManager swSkMgr = swModel.SketchManager;
            SketchSegment swSkSgm = default(SketchSegment);
            ModelDocExtension swModelDocExtension = default(ModelDocExtension);
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            FeatureManager swFeatureMgr = default(FeatureManager);
            Feature swFeature = default(Feature);
            ExtrudeFeatureData2 swExtrudeFeatureData = default(ExtrudeFeatureData2);

            bool status = false;
            object[] skcontours = null;
            SketchContour skcontour = null;
            int nbrContours = 0;
            int i = 0;

            swModelDocExtension = swModel.Extension;
            swSkMgr = swModel.SketchManager;
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swFeatureMgr = (FeatureManager)swModel.FeatureManager;

            ////Create sketch containing sketch contours
            //swSkMgr.InsertSketch(true);
            //SketchSegment swSketchSegment = (SketchSegment)swSkMgr.CreateCircle(0.0, 0.0, 0.0, 0.010564, -0.041843, 0.0);
            //swSketchSegment = (SketchSegment)swSkMgr.CreateCircle(0.043155, 0.0, 0.0, 0.048428, -0.01221, 0.0);

            //swSketchSegment = (SketchSegment)swSkMgr.CreateCircle(-0.043155, 0.0, 0.0, -0.043214, -0.014954, 0.0);

            //swSkMgr.InsertSketch(true);

            //Create boss extrude feature
            //status = swModelDocExtension.SelectByID2("草图4", "SKETCH", 0, 0, 0, false, 0, null, 0);
            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", -0.047096875714166, 0.00724922083273226, 0.018531938896921, true, 0, null, 0);
            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", 0.0473122625955432, -0.015948285832011, -0.0155264330079864, true, 0, null, 0);
            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", -0.00880361157802517, -0.0246473508312897, 0.0199951653548178, true, 0, null, 0);
            swModel.ClearSelection2(true);

            swSelectionMgr.EnableContourSelection = true;

            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", -0.047096875714166, 0.00724922083273226, 0.018531938896921, true, 4, null, 0);
            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", 0.0473122625955432, -0.015948285832011, -0.0155264330079864, true, 4, null, 0);
            status = swModelDocExtension.SelectByID2("草图4", "SKETCHCONTOUR", -0.00880361157802517, -0.0246473508312897, 0.0199951653548178, true, 4, null, 0);
            swFeature = swFeatureMgr.FeatureExtrusion3(true, false, false, 0, 0, 0.01016, 0.00254, false, false, false,
            false, 0.0174532925199433, 0.0174532925199433, false, false, false, false, true, true, true,
            0, 0, false);
            swSelectionMgr.EnableContourSelection = false;


        }

        private void button5_Click(object sender, EventArgs e)
        {
            swApp = Utility.ConnectToSolidWorks();

            ModelDoc2 activeDoc = (ModelDoc2)swApp.ActiveDoc;
            DrawingDoc drawDoc = (DrawingDoc)activeDoc;
            //drawDoc.CreateDrawViewFromModelView3();

            View activeView = (View)drawDoc.GetFirstView();

            Debug.Print(drawDoc.GetViewCount().ToString());



        }

        private void button6_Click(object sender, EventArgs e)
        {
            SldWorks swApp = Utility.ConnectToSolidWorks();
            if (swApp == null)
            {

                return;
            }

            ModelDoc2 modelDoc = swApp.IActiveDoc2;
            // 获得两配合面
            SelectionMgr selectMgr = modelDoc.ISelectionManager;

            //Face2 faceSelectFace1 = (Face2)selectMgr.GetSelectedObject6(1, -1);
            //Face2 faceSelectFace2 = (Face2)selectMgr.GetSelectedObject6(2, -1);




            // 获得选择点1信息
            double[] p1 = (double[])selectMgr.GetSelectionPoint(1);
            // 获得选择点2信息
            double[] p2 = (double[])selectMgr.GetSelectionPoint(2);

            p1 = p1.Select(x => x * 1000).ToArray();
            p2 = p2.Select(x => x * 1000).ToArray();


            Point3d selectionPoint1 = new Point3d(p1[0], p1[1], p1[2]);
            Point3d selectionPoint2 = new Point3d(p2[0], p2[1], p2[2]);

            double[] vectorX = { 1, 0, 0 };
            double[] vectorXY = { 1, 0, 1 };

            Coord3d coord = new Coord3d(selectionPoint1, vectorX, vectorXY);

            // 通过点位置判断
            selectionPoint1 = selectionPoint1.ConvertTo(coord);
            selectionPoint2 = selectionPoint2.ConvertTo(coord);

            Debug.Print($"点位置增量为：{selectionPoint2.X},{selectionPoint2.Y},{selectionPoint2.Z}");

            // 通过构造向量判断
            Vector3d vector = new Vector3d(selectionPoint1, selectionPoint2);
            if (vector.X > 0)
            {
                if (vector.Y > 0)
                {
                    if (vector.Z > 0)
                    {
                        Console.WriteLine("朝向 右上前");
                    }
                    else if (vector.Z < 0)
                    {
                        Console.WriteLine("朝向 右上后");
                    }
                    else
                    {
                        Console.WriteLine("朝向右上，Z=0");
                    }
                }
                else if (vector.Y < 0)
                {
                    if (vector.Z > 0)
                    {
                        Console.WriteLine("朝向 右下前");
                    }
                    else if (vector.Z < 0)
                    {
                        Console.WriteLine("朝向右下后");
                    }
                    else
                    {
                        Console.WriteLine("朝向右下，Z=0");
                    }
                }
                else
                {
                    if (vector.Z != 0)
                    {
                        Console.WriteLine("向量位于X正Z轴");
                    }
                    else
                    {
                        Console.WriteLine("向量位于X正轴");
                    }
                }
            }
            else if (vector.X < 0)
            {
                if (vector.Y > 0)
                {
                    if (vector.Z > 0)
                    {
                        Console.WriteLine("向量位于第二象限");
                    }
                    else if (vector.Z < 0)
                    {
                        Console.WriteLine("向量位于第七象限");
                    }
                    else
                    {
                        Console.WriteLine("向量位于X负Y正轴");
                    }
                }
                else if (vector.Y < 0)
                {
                    if (vector.Z > 0)
                    {
                        Console.WriteLine("向量位于第三象限");
                    }
                    else if (vector.Z < 0)
                    {
                        Console.WriteLine("向量位于第六象限");
                    }
                    else
                    {
                        Console.WriteLine("向量位于X负Y负轴");
                    }
                }
                else
                {
                    if (vector.Z != 0)
                    {
                        Console.WriteLine("向量位于X负Z轴");
                    }
                    else
                    {
                        Console.WriteLine("向量位于X负轴");
                    }
                }
            }
            else
            {
                if (vector.Y > 0)
                {
                    if (vector.Z != 0)
                    {
                        Console.WriteLine("向量位于Y正Z轴");
                    }
                    else
                    {
                        Console.WriteLine("向量位于Y正轴");
                    }
                }
                else if (vector.Y < 0)
                {
                    if (vector.Z != 0)
                    {
                        Console.WriteLine("向量位于Y负Z轴");
                    }
                    else
                    {
                        Console.WriteLine("向量位于Y负轴");
                    }
                }
                else
                {
                    if (vector.Z != 0)
                    {
                        Console.WriteLine("向量位于Z轴");
                    }
                    else
                    {
                        Console.WriteLine("向量位于原点");
                    }
                }
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //SolidWorksVersion solidWorksVersion = SolidWorksVersion.SolidWorks2020;
            SldWorks swApp = Connect.GetRunningSolidWorks();


            ModelDoc2 activeDoc = swApp.IActiveDoc2;
            PartDoc prtDoc = (PartDoc)activeDoc;
            FeatureManager featMgr = swModel.FeatureManager;

            double[] sheetBox = (double[])prtDoc.GetPartBox(false);



            Feature feat = swModel.IFirstFeature();

            while (feat != null)
            {
                var featTypeName = feat.GetTypeName2();
                Debug.Print(featTypeName);
                if (featTypeName == "SMBaseFlange")
                {
                    break;
                }
                feat = feat.IGetNextFeature();
            }
            BaseFlangeFeatureData baseFlangeFeat = (BaseFlangeFeatureData)feat.IGetDefinition();

            //折弯半径
            var r = baseFlangeFeat.BendRadius;
            //铜排厚度
            var thickness = baseFlangeFeat.Thickness;
            //k因子
            var k = baseFlangeFeat.KFactor;
            // 铜排长度
            var length = sheetBox[3] - sheetBox[0];
        }
        int val = 0;
        private List<Component2> compTarget;    // 开孔组件列表
        private List<Face2> faceTarget;         // 开孔面列表
        private List<Face2> faceBaseList;       // 孔基准面列表
        private void button8_Click(object sender, EventArgs e)
        {
            swApp = Connect.GetRunningSolidWorks();
            ModelDoc2 acitveDoc = swApp.IActiveDoc2;
            SelectionMgr selMgr = acitveDoc.ISelectionManager;

            UserPMPForOpenHole userPmp = new UserPMPForOpenHole(swApp);
            userPmp.Show();

        }

        private void btnDelSegMentMate_Click(object sender, EventArgs e)
        {
            swApp = Connect.GetRunningSolidWorks();
            ModelDoc2 acitveDoc = swApp.IActiveDoc2;
            SketchManager skMgr = acitveDoc.SketchManager;
            Sketch mappingSketch = skMgr.ActiveSketch;

            object[] mappingSketchContours = (object[])mappingSketch.GetSketchContours();
            


            int numContours = mappingSketchContours.Length;
            for (int i = 0; i < numContours; i++)
            {
                SketchContour countour = (SketchContour)mappingSketchContours[i];
                //var edgesCount = countour.GetEdgesCount();  // 当前草图轮廓所包含的边线数量
                object[] countourSegments = (object[])countour.GetSketchSegments();
                var edgesCount = countourSegments.Length;    // 当前草图轮廓所包含的边线数量


                // 删除约束关系
                if (edgesCount == 1)  // 如果是圆孔
                {
                    //countour.Select(true, -1);
                    SketchSegment skSeg = (SketchSegment)countourSegments[0];
                    skSeg.Select(true);

                    acitveDoc.SketchConstraintsDel(0, "sgOFFSETEDGE");
                }
            }
        }
    }
}



